This course is to give the understanding of open data, open science, and open research tools.
I am feeling confused and a bit stressed. But also excited as well.
My expectations are:
Then just a couple of lists to learn to make the lists:
I heard from this course from my colleague.
Here is the link to my github repository https://github.com/tiinasip/IODS-project
And here is the link to my diary https://tiinasip.github.io/IODS-project/
Another way to add the link to my diary
Work summary I have went through Data camp parts R short and sweet and Regression and model validation. I have also listened a couple of statistics classes from YouTube and went through the chapters 3 & 4 from Kimmo’s textbook.
I have learned some basics in R and refreshed my knowledge about regression analysis.
Code for data creation is available at https://github.com/tiinasip/IODS-project/blob/master/data/create_learning2014.R
Code for data analysis (although it is thoroughly described in this report) https://github.com/tiinasip/IODS-project/blob/master/Exercise2_AnalysisPart.R
Data was collected in a survey for students attending statistics course. The aim was to find out, which factors have effect on course success. Originally there were many questions that were now grouped to be strategic, surface and deep questions.
Analysis starts with reading the data and taking the summary:
learnings2 <- read.table("http://s3.amazonaws.com/assets.datacamp.com/production/course_2218/datasets/learning2014.txt ", sep=",", header=TRUE)
dim(learnings2)
str(learnings2)
summary(learnings2)
dim(learnings2)
## [1] 166 7
str(learnings2)
## 'data.frame': 166 obs. of 7 variables:
## $ gender : Factor w/ 2 levels "F","M": 1 2 1 2 2 1 2 1 2 1 ...
## $ age : int 53 55 49 53 49 38 50 37 37 42 ...
## $ attitude: num 3.7 3.1 2.5 3.5 3.7 3.8 3.5 2.9 3.8 2.1 ...
## $ deep : num 3.58 2.92 3.5 3.5 3.67 ...
## $ stra : num 3.38 2.75 3.62 3.12 3.62 ...
## $ surf : num 2.58 3.17 2.25 2.25 2.83 ...
## $ points : int 25 12 24 10 22 21 21 31 24 26 ...
summary(learnings2)
## gender age attitude deep stra
## F:110 Min. :17.00 Min. :1.400 Min. :1.583 Min. :1.250
## M: 56 1st Qu.:21.00 1st Qu.:2.600 1st Qu.:3.333 1st Qu.:2.625
## Median :22.00 Median :3.200 Median :3.667 Median :3.188
## Mean :25.51 Mean :3.143 Mean :3.680 Mean :3.121
## 3rd Qu.:27.00 3rd Qu.:3.700 3rd Qu.:4.083 3rd Qu.:3.625
## Max. :55.00 Max. :5.000 Max. :4.917 Max. :5.000
## surf points
## Min. :1.583 Min. : 7.00
## 1st Qu.:2.417 1st Qu.:19.00
## Median :2.833 Median :23.00
## Mean :2.787 Mean :22.72
## 3rd Qu.:3.167 3rd Qu.:27.75
## Max. :4.333 Max. :33.00
There are 166 rows and 7 variables/columns. 7 variables are: gender, age, attitude, deep, stra, surf and points. Gender is factor (male/female), age and points are integer, attiture, deep , stra and surf are numeric.
Medians and means seem to be quite close to each other, which is one indication of normal distribution but does not confirm it alone.
pairs(learnings2[-1],col = learnings2$gender, main="Graphical summary")
The scatter plot shows low correlations to other combinations thant points and attitude. For instance, stra and surf seem to have no correlations as the points are distributed widely. There is no clear positive, negative or curved correlation clearly visible in the figure.
Analysis is continued with a more detailed graphical analysis of variables. First without gender graphical summary.
library(GGally)
## Loading required package: ggplot2
## Registered S3 method overwritten by 'GGally':
## method from
## +.gg ggplot2
library(ggplot2)
ggpairs(learnings2, mapping = aes(), title="Scatter plot matrix, no gender as column ",lower = list(combo = wrap("facethist", bins = 20)))
And then by gender
# create a more advanced plot matrix with ggpairs()
ggpairs(learnings2, mapping = aes(col=gender, alpha = 0.3), title="Graphical summary and gender ",
lower = list(combo = wrap("facethist", bins = 20))
)
#Distributions Age distribution is right-tailed, deep is left-tailed, especially for males. Strategic distribution is approximately symmetrical, especially for males. Surface is also quite symmetric. Attitude is interesting. When both genders are in, it looks quite symmetric. But for males it is left-tailed Points are bimodally distributed or for males even multimodal. Gender is nominal measurement meaning the categories are mutually exclusive and have no logical order.
If the correlation is between +/- 0.5 and +/-1, the correlation could be strong. Only points and attitude correlation (0.437) is close to that, which indicates that they have the strongest connection in the data and other variables are not that meaningful. The second highest correlation is between surf and deep, but it is -0.324.
#Regression Three variables selected as explanatory are: - Attitude - Strategic - Surface They were selected, because they had highest absolute correlations (0,437,0,146 and 0,144) with the points, which is our target variable.
First the model with only attitude
qplot(attitude, points, data = learnings2) + geom_smooth(method = "lm")
my_model <- lm(points ~ attitude, data = learnings2)
summary(my_model)
##
## Call:
## lm(formula = points ~ attitude, data = learnings2)
##
## Residuals:
## Min 1Q Median 3Q Max
## -16.9763 -3.2119 0.4339 4.1534 10.6645
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 11.6372 1.8303 6.358 1.95e-09 ***
## attitude 3.5255 0.5674 6.214 4.12e-09 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 5.32 on 164 degrees of freedom
## Multiple R-squared: 0.1906, Adjusted R-squared: 0.1856
## F-statistic: 38.61 on 1 and 164 DF, p-value: 4.119e-09
my_model <- lm(points ~ attitude, data = learnings2)
results <- summary(my_model)
P values of both intercept and attitude are under 0.05 indicating significant statistic correlation. T value is >2 indicating that as well.
Validation of graphical model is below. Normal Q-Q shows that both attitude and points seem to come from the same distribution, forming a line that’s roughly straight. It seems that the variables are normally distributed, although some pairs both at the beginning and at the end are not following the line.
Residuals vs. fitted tests, if the relationship of the variables is linear. If the plot is relatively shapeless, there are no obvious outliers and the data is generally symmetrically around 0 line, it is indicating linearity. In this case the plot is quite good as there is no pattern. There are some outliers, but not many and the values are around 0.
plot(my_model, which=c(1,2,5))
Also residuals vs. leverage figure indicates that there are no significant outliers. There are no many points in outside Cook’s distance line meaning there are not outliers that would change the regression result if I exclude those cases.
Next step is to add stra to the model and check the summary.
my_model2 <- lm(points ~ attitude + stra, data = learnings2)
summary(my_model2)
##
## Call:
## lm(formula = points ~ attitude + stra, data = learnings2)
##
## Residuals:
## Min 1Q Median 3Q Max
## -17.6436 -3.3113 0.5575 3.7928 10.9295
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 8.9729 2.3959 3.745 0.00025 ***
## attitude 3.4658 0.5652 6.132 6.31e-09 ***
## stra 0.9137 0.5345 1.709 0.08927 .
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 5.289 on 163 degrees of freedom
## Multiple R-squared: 0.2048, Adjusted R-squared: 0.1951
## F-statistic: 20.99 on 2 and 163 DF, p-value: 7.734e-09
Third model is created by adding both stra and surf to the first model and check if the model is improved.
my_model3 <- lm(points ~ attitude + stra + surf, data = learnings2)
summary(my_model3)
##
## Call:
## lm(formula = points ~ attitude + stra + surf, data = learnings2)
##
## Residuals:
## Min 1Q Median 3Q Max
## -17.1550 -3.4346 0.5156 3.6401 10.8952
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 11.0171 3.6837 2.991 0.00322 **
## attitude 3.3952 0.5741 5.913 1.93e-08 ***
## stra 0.8531 0.5416 1.575 0.11716
## surf -0.5861 0.8014 -0.731 0.46563
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 5.296 on 162 degrees of freedom
## Multiple R-squared: 0.2074, Adjusted R-squared: 0.1927
## F-statistic: 14.13 on 3 and 162 DF, p-value: 3.156e-08
The second model with attitude and stra does not seem to create the model better. Stra’s p value is >0.05 meaning it is not statistically significant and could be dropped from the model.
The third model with attitude, stra and surf ends up to the same conclusion. Both stra and surf have p value >0.05 meaning they could be dropped from the model.It is adviced that one should choose the simple model when adding the variables does not improve the model.
But when the adjusted R-squares are checked, the situation changes. The adjusted R-squared compares the explanatory power of regression models that contain different numbers of predictors. Adjusted R-square of the model is 0.1856. The second model has adjusted R-square 0.1951. The third model has adjusted R-squared 0.1927. However, all these adjusted R values are low. Adjusted R-square tells the proportion of the variability in the dependent variable that is explained by the model.
I check still the diagnostics of model 2 regressio, but their output is very similar to the diagnostics of the first model.
plot(my_model2, which=c(1,2,5))
It is generally advisable to use simpler model when possible. As additional coefficients did not create clearly better model, I would use the simple points ~ attitude model.
Work summary
Code for data creation is available at https://github.com/tiinasip/IODS-project/blob/master/data/create_alc.R
Code for data analysis (although it is thoroughly described in this report) https://github.com/tiinasip/IODS-project/blob/master/data/alc_analysis.R
Data is about student achievent in seconday education of two Portuguese schools.The data attributes include student grades, demographic, social and school related features) and it was collected by using school reports and questionnaires. The purpose of the analysis to find relationships between high or low alcohol consumption and other variables available.
Analysis starts with reading the data and taking the summary:
alc <- read.table("http://s3.amazonaws.com/assets.datacamp.com/production/course_2218/datasets/alc.txt", sep=",", header=TRUE)
dim(alc)
str(alc)
summary(alc)
library(GGally)
library(ggplot2)
library(dplyr)
##
## Attaching package: 'dplyr'
## The following object is masked from 'package:GGally':
##
## nasa
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
library(tidyr)
gather(alc) %>% ggplot(aes(value)) + facet_wrap("key", scales = "free")+geom_bar()
## Warning: attributes are not identical across measure variables;
## they will be dropped
alc_gender <- ggplot(alc, aes(x = high_use, y = G3, col=sex))
alc_gender + geom_boxplot(outlier.colour="green") + ylab("grade")+ggtitle("Student grades by alcohol consumption and sex, outliers green")
There are some outliers, which are coloured green.Next check the crosstables between gender and high use.
alc_gender_table <-table(alc$sex,alc$high_use)
prop.table(alc_gender_table,2) #based on column totals
##
## FALSE TRUE
## F 0.5814815 0.3660714
## M 0.4185185 0.6339286
prop.table(alc_gender_table,1) #based on row totals
##
## FALSE TRUE
## F 0.7929293 0.2070707
## M 0.6141304 0.3858696
g1_ge <- ggplot(data = alc, aes(x = high_use, fill=sex))
g1_ge + geom_bar()+ggtitle("Gender and high alcohol use")
Gender in the data follows binomial distribution. 63 % of high users are males.Also the percentage of high users is higher for males (39%) than females (21%)
alc_higher <- ggplot(alc, aes(x = high_use, y = G3, col=higher))
alc_higher + geom_boxplot(outlier.colour="green") + ylab("grade")+ggtitle("Student grades by alcohol consumption and higher education")
alc_higher_table <-table(alc$higher,alc$high_use)
prop.table(alc_higher_table,2) #based on column totals
##
## FALSE TRUE
## no 0.03333333 0.08035714
## yes 0.96666667 0.91964286
prop.table(alc_higher_table,1) #based on row totals
##
## FALSE TRUE
## no 0.500000 0.500000
## yes 0.717033 0.282967
g1_hi <- ggplot(data = alc, aes(x = high_use, fill=higher))
g1_hi + geom_bar()+ggtitle("Higher education target and high alcohol use")
Higher education target follows binomial distribution.8 % of high users are not targetting higher indicating that higher education target may not explain much of high use. Also the percentage of high use is only 50 % for students not targeting higher education.
alc_romantic <- ggplot(alc, aes(x = high_use, y = G3, col=romantic))
alc_romantic + geom_boxplot(outlier.colour="green") + ylab("grade")+ggtitle("Student grades by alcohol consumption and romantic relationship")
alc_romantic_table <-table(alc$romantic,alc$high_use)
prop.table(alc_romantic_table,2) #based on column totals
##
## FALSE TRUE
## no 0.6740741 0.7053571
## yes 0.3259259 0.2946429
prop.table(alc_romantic_table,1) #based on row totals
##
## FALSE TRUE
## no 0.6973180 0.3026820
## yes 0.7272727 0.2727273
g1_ro <- ggplot(data = alc, aes(x = high_use, fill=romantic))
g1_ro + geom_bar()+ggtitle("Romantic relationship and high alcohol use")
Romantic relationship ollows binomial distribution.71 % of high users are not in romantic relationship. However, the share of high user from students having romantic relationship is 27% and from students not having relationship 30%. It seems that romantic relationship may not explain much.
alc$studytime <-as.factor(alc$studytime)
alc_studytime <- ggplot(alc, aes(x = studytime, y = G3, col=high_use))
alc_studytime + geom_boxplot(outlier.colour="red") + ylab("grade")+ggtitle("Student grades by alcohol consumption and weekly studytime")
alc_studytime_table <-table(alc$studytime,alc$high_use)
prop.table(alc_studytime_table,2) #based on column totals
##
## FALSE TRUE
## 1 0.22222222 0.38392857
## 2 0.49259259 0.50892857
## 3 0.20000000 0.07142857
## 4 0.08518519 0.03571429
prop.table(alc_studytime_table,1) #based on row totals
##
## FALSE TRUE
## 1 0.5825243 0.4174757
## 2 0.7000000 0.3000000
## 3 0.8709677 0.1290323
## 4 0.8518519 0.1481481
g1_st <- ggplot(data = alc, aes(x = studytime, fill=high_use))
g1_st + geom_bar()+ggtitle("Studytime and high alcohol use")
Studytime follows ordinal scale. The percentages of high users are highest in studytime groups 1 and 2 (38% and 51%, respectively). The share of high users in studytime group 1 is the highest (42%). Surprisingly, the highest median grade is among high users whose study a lot. But for non-high-users the highest median is in the studytime group 3. However, n is much lower in studytime groups 3 and 4, so individiual performance influences more.
alc_activities <- ggplot(alc, aes(x = high_use, y = G3, col=activities))
alc_activities + geom_boxplot(outlier.colour="green") + ylab("grade")+ggtitle("Student grades by alcohol consumption and activities")
alc_activities_table <-table(alc$activities,alc$high_use)
prop.table(alc_activities_table,2) #based on column totals
##
## FALSE TRUE
## no 0.4518519 0.5267857
## yes 0.5481481 0.4732143
prop.table(alc_activities_table,1) #based on row totals
##
## FALSE TRUE
## no 0.6740331 0.3259669
## yes 0.7363184 0.2636816
g1_ac <- ggplot(data = alc, aes(x = high_use, fill=activities))
g1_ac + geom_bar()+ggtitle("Activities and high alcohol use")
Activities follow binomial distribution.53 % of high users are not doing activities. However, the share of high user from students having activities is 27% and from students not having activites 33%. It seems that activities may not explain much.
As a conclusion it seems that my chosen variables are not explaining much. Sex and studytime seem to be the srongest candidates. Next I create model.
# find the model with glm()
m <- glm(high_use ~ sex + higher+ romantic + activities + studytime, data = alc, family = "binomial")
summary(m)
##
## Call:
## glm(formula = high_use ~ sex + higher + romantic + activities +
## studytime, family = "binomial", data = alc)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -1.2851 -0.8818 -0.6724 1.2023 2.1803
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -0.36148 0.56212 -0.643 0.52018
## sexM 0.68577 0.25344 2.706 0.00681 **
## higheryes -0.38258 0.51758 -0.739 0.45980
## romanticyes -0.07465 0.26167 -0.285 0.77541
## activitiesyes -0.30089 0.24016 -1.253 0.21025
## studytime2 -0.25227 0.27284 -0.925 0.35517
## studytime3 -1.15983 0.45238 -2.564 0.01035 *
## studytime4 -1.10844 0.59105 -1.875 0.06074 .
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 462.21 on 381 degrees of freedom
## Residual deviance: 432.87 on 374 degrees of freedom
## AIC: 448.87
##
## Number of Fisher Scoring iterations: 4
#coefficients
coef(m)
## (Intercept) sexM higheryes romanticyes activitiesyes
## -0.36148480 0.68577438 -0.38258312 -0.07465366 -0.30089256
## studytime2 studytime3 studytime4
## -0.25227181 -1.15983304 -1.10843894
From model it is clear that only sex and studytime are significant in the model. For others Pr(>|z|) is more than 0.05. I had five hypothesis and two of them were true in the sample indicating that there is a relationship in the population. Other 3 hypothesis were rejected based on the sample.
Odds ratio greater than one means odds are getting larger. Only sex is more than one so it is increasing odds that the student is a high-user. Odds ratio less than one means odds are getting smaller. Studytime has the smallest odds ratio. Confidence interval of studytime is (0.47, 0.87) meaning it remains under 1. Respectively sex’s confidence interval remains clearly over 1 (1.21, 3.25). On the other hand, non-meaningful variables have confidence intervals having values below and above 1 indicating that odds ratio is not significant for decision making.
# compute odds ratios (OR)
OR <- coef(m) %>% exp
# compute confidence intervals (CI)
CI <-confint(m)%>% exp
## Waiting for profiling to be done...
# print out the odds ratios with their confidence intervals
cbind(OR, CI)
## OR 2.5 % 97.5 %
## (Intercept) 0.6966412 0.22877627 2.1168399
## sexM 1.9853086 1.21136731 3.2780894
## higheryes 0.6820972 0.24452974 1.9096568
## romanticyes 0.9280649 0.55145455 1.5424153
## activitiesyes 0.7401573 0.46121490 1.1844172
## studytime2 0.7770335 0.45603512 1.3317371
## studytime3 0.3135385 0.12224825 0.7335040
## studytime4 0.3300738 0.09000723 0.9651789
As higher, romantic and activities were not significant, a new model is created and used for prediction as instructed.
m2 <- glm(high_use ~ sex + studytime, data = alc, family = "binomial")
summary(m2)
##
## Call:
## glm(formula = high_use ~ sex + studytime, family = "binomial",
## data = alc)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -1.1060 -0.8527 -0.7405 1.2506 2.1042
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -0.8246 0.2763 -2.985 0.00284 **
## sexM 0.6543 0.2460 2.659 0.00783 **
## studytime2 -0.3292 0.2658 -1.239 0.21540
## studytime3 -1.2735 0.4439 -2.869 0.00412 **
## studytime4 -1.2025 0.5858 -2.053 0.04010 *
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 462.21 on 381 degrees of freedom
## Residual deviance: 435.28 on 377 degrees of freedom
## AIC: 445.28
##
## Number of Fisher Scoring iterations: 4
#coefficients
coef(m2)
## (Intercept) sexM studytime2 studytime3 studytime4
## -0.8246325 0.6542694 -0.3292488 -1.2735443 -1.2025286
Odds ratios and confidence intervals of new model.
# compute odds ratios (OR)
OR <- coef(m2) %>% exp
# compute confidence intervals (CI)
CI <-confint(m2)%>% exp
## Waiting for profiling to be done...
# print out the odds ratios with their confidence intervals
cbind(OR, CI)
## OR 2.5 % 97.5 %
## (Intercept) 0.4383961 0.25246554 0.7477169
## sexM 1.9237365 1.19050659 3.1290488
## studytime2 0.7194640 0.42763809 1.2143282
## studytime3 0.2798380 0.11064760 0.6421976
## studytime4 0.3004336 0.08256457 0.8676192
# predict() the probability of high_use
probabilities <- predict(m2, type = "response")
# add the predicted probabilities to 'alc'
alc <- mutate(alc, probability = probabilities)
# use the probabilities to make a prediction of high_use
alc <- mutate(alc, prediction = probability>0.5)
# see the last ten original classes, predicted probabilities, and class predictions
select(alc, sex, studytime, high_use, probability, prediction) %>% tail(10)
## sex studytime high_use probability prediction
## 373 M 1 FALSE 0.4575119 FALSE
## 374 M 1 TRUE 0.4575119 FALSE
## 375 F 3 FALSE 0.1092742 FALSE
## 376 F 1 FALSE 0.3047812 FALSE
## 377 F 3 FALSE 0.1092742 FALSE
## 378 F 2 FALSE 0.2397809 FALSE
## 379 F 2 FALSE 0.2397809 FALSE
## 380 F 2 FALSE 0.2397809 FALSE
## 381 M 1 TRUE 0.4575119 FALSE
## 382 M 1 TRUE 0.4575119 FALSE
Binary predictions in figure:
#a plot of 'high_use' versus 'probability' in 'alc'
g <- ggplot(alc, aes(x = probability, y = high_use, col=prediction))
g+geom_point(aes(col=prediction))
The model predict correctly in 270 cases of non-users. But the model did not predict any high-users at all. The same prediction power is just always guess that the student is not a high-user, and it is actually a relevant idea compared to the bad model, because 71 % of students in the survey were not high-users.
# tabulate the target variable versus the predictions
table(high_use = alc$high_use, prediction = alc$prediction)
## prediction
## high_use FALSE
## FALSE 270
## TRUE 112
table(high_use = alc$high_use, prediction = alc$prediction) %>% prop.table() %>% addmargins()
## prediction
## high_use FALSE Sum
## FALSE 0.7068063 0.7068063
## TRUE 0.2931937 0.2931937
## Sum 1.0000000 1.0000000
Analysis by models have advantages over guessing. In this case guessing produced good candidates, but the analysis showed their weaknesses. On the other hand, there were probably many other variables which had had significance but I did not take them into analysis because of my prejudices.
Work summary
Codes are available at
Boston dataset contains information collected by the U.S Census Service concerning housing valuesin the area of Boston Mass. It was obtained from the StatLib archive. More information about each variable can be found in here
Descriptions of variables are:
library(MASS)
data("Boston")
dim(Boston)
## [1] 506 14
str(Boston)
## 'data.frame': 506 obs. of 14 variables:
## $ crim : num 0.00632 0.02731 0.02729 0.03237 0.06905 ...
## $ zn : num 18 0 0 0 0 0 12.5 12.5 12.5 12.5 ...
## $ indus : num 2.31 7.07 7.07 2.18 2.18 2.18 7.87 7.87 7.87 7.87 ...
## $ chas : int 0 0 0 0 0 0 0 0 0 0 ...
## $ nox : num 0.538 0.469 0.469 0.458 0.458 0.458 0.524 0.524 0.524 0.524 ...
## $ rm : num 6.58 6.42 7.18 7 7.15 ...
## $ age : num 65.2 78.9 61.1 45.8 54.2 58.7 66.6 96.1 100 85.9 ...
## $ dis : num 4.09 4.97 4.97 6.06 6.06 ...
## $ rad : int 1 2 2 3 3 3 5 5 5 5 ...
## $ tax : num 296 242 242 222 222 222 311 311 311 311 ...
## $ ptratio: num 15.3 17.8 17.8 18.7 18.7 18.7 15.2 15.2 15.2 15.2 ...
## $ black : num 397 397 393 395 397 ...
## $ lstat : num 4.98 9.14 4.03 2.94 5.33 ...
## $ medv : num 24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...
summary(Boston)
## crim zn indus chas
## Min. : 0.00632 Min. : 0.00 Min. : 0.46 Min. :0.00000
## 1st Qu.: 0.08204 1st Qu.: 0.00 1st Qu.: 5.19 1st Qu.:0.00000
## Median : 0.25651 Median : 0.00 Median : 9.69 Median :0.00000
## Mean : 3.61352 Mean : 11.36 Mean :11.14 Mean :0.06917
## 3rd Qu.: 3.67708 3rd Qu.: 12.50 3rd Qu.:18.10 3rd Qu.:0.00000
## Max. :88.97620 Max. :100.00 Max. :27.74 Max. :1.00000
## nox rm age dis
## Min. :0.3850 Min. :3.561 Min. : 2.90 Min. : 1.130
## 1st Qu.:0.4490 1st Qu.:5.886 1st Qu.: 45.02 1st Qu.: 2.100
## Median :0.5380 Median :6.208 Median : 77.50 Median : 3.207
## Mean :0.5547 Mean :6.285 Mean : 68.57 Mean : 3.795
## 3rd Qu.:0.6240 3rd Qu.:6.623 3rd Qu.: 94.08 3rd Qu.: 5.188
## Max. :0.8710 Max. :8.780 Max. :100.00 Max. :12.127
## rad tax ptratio black
## Min. : 1.000 Min. :187.0 Min. :12.60 Min. : 0.32
## 1st Qu.: 4.000 1st Qu.:279.0 1st Qu.:17.40 1st Qu.:375.38
## Median : 5.000 Median :330.0 Median :19.05 Median :391.44
## Mean : 9.549 Mean :408.2 Mean :18.46 Mean :356.67
## 3rd Qu.:24.000 3rd Qu.:666.0 3rd Qu.:20.20 3rd Qu.:396.23
## Max. :24.000 Max. :711.0 Max. :22.00 Max. :396.90
## lstat medv
## Min. : 1.73 Min. : 5.00
## 1st Qu.: 6.95 1st Qu.:17.02
## Median :11.36 Median :21.20
## Mean :12.65 Mean :22.53
## 3rd Qu.:16.95 3rd Qu.:25.00
## Max. :37.97 Max. :50.00
According to the information the Boston data frame has 506 rows and 14 columns. That is equal to my check. All variables are either numeric or int. There is no missing values either:
sum(is.na(Boston))
## [1] 0
mean(is.na(Boston))
## [1] 0
From graphical overview it is easy to notice at least the following:
library(GGally)
library(ggplot2)
ggpairs(Boston, title=“Scatter plot matrix, distributions”,lower = list( continuous = “smooth”,mapping = aes()))
Scatter plot matrix
pairs(Boston[-1], main="Graphical summary")
Scaling targets to normalising:
boston_scaled <- scale(Boston)
summary(boston_scaled)
## crim zn indus
## Min. :-0.419367 Min. :-0.48724 Min. :-1.5563
## 1st Qu.:-0.410563 1st Qu.:-0.48724 1st Qu.:-0.8668
## Median :-0.390280 Median :-0.48724 Median :-0.2109
## Mean : 0.000000 Mean : 0.00000 Mean : 0.0000
## 3rd Qu.: 0.007389 3rd Qu.: 0.04872 3rd Qu.: 1.0150
## Max. : 9.924110 Max. : 3.80047 Max. : 2.4202
## chas nox rm age
## Min. :-0.2723 Min. :-1.4644 Min. :-3.8764 Min. :-2.3331
## 1st Qu.:-0.2723 1st Qu.:-0.9121 1st Qu.:-0.5681 1st Qu.:-0.8366
## Median :-0.2723 Median :-0.1441 Median :-0.1084 Median : 0.3171
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.:-0.2723 3rd Qu.: 0.5981 3rd Qu.: 0.4823 3rd Qu.: 0.9059
## Max. : 3.6648 Max. : 2.7296 Max. : 3.5515 Max. : 1.1164
## dis rad tax ptratio
## Min. :-1.2658 Min. :-0.9819 Min. :-1.3127 Min. :-2.7047
## 1st Qu.:-0.8049 1st Qu.:-0.6373 1st Qu.:-0.7668 1st Qu.:-0.4876
## Median :-0.2790 Median :-0.5225 Median :-0.4642 Median : 0.2746
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.6617 3rd Qu.: 1.6596 3rd Qu.: 1.5294 3rd Qu.: 0.8058
## Max. : 3.9566 Max. : 1.6596 Max. : 1.7964 Max. : 1.6372
## black lstat medv
## Min. :-3.9033 Min. :-1.5296 Min. :-1.9063
## 1st Qu.: 0.2049 1st Qu.:-0.7986 1st Qu.:-0.5989
## Median : 0.3808 Median :-0.1811 Median :-0.1449
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.4332 3rd Qu.: 0.6024 3rd Qu.: 0.2683
## Max. : 0.4406 Max. : 3.5453 Max. : 2.9865
When summary of scaled data is compared to the summary of the original data, it is obvious that magnitudes of min and max values have decreased and mean is always 0. For instance, max of lstat was 37.97 and after scaling 3.54, respectively black max 396.9 and 0.44. Zn min was 0, now -0.49, rm min was 3.56, now -3.88.
Next, categorial variable crim and its quantiles are calculated:
# change the object to data frame, because vector otherwise causes an error in next phase
boston_scaled<-as.data.frame(boston_scaled)
bins <- quantile(boston_scaled$crim)
bins
## 0% 25% 50% 75% 100%
## -0.419366929 -0.410563278 -0.390280295 0.007389247 9.924109610
crime <- cut(boston_scaled$crim, breaks = bins, include.lowest = TRUE, labels = c("low", "med_low", "med_high", "high"))
table(crime)
## crime
## low med_low med_high high
## 127 126 126 127
# remove original crim from the dataset
boston_scaled <- dplyr::select(boston_scaled, -crim)
# add the new categorical value to scaled data
boston_scaled <- data.frame(boston_scaled, crime)
Testing and training sets are created:
# number of rows in the Boston dataset
n <- nrow(boston_scaled)
# randomly 80% of the rows
ind <- sample(n, size = n * 0.8)
# creating train set
train <- boston_scaled[ind,]
# create testing set
test <- boston_scaled[-ind,]
# save the correct classes from test data
correct_classes <- test$crime
# remove the crime variable from test data
test <- dplyr::select(test, -crime)
Classification method LDA is used to findthe variables that separate the classes best and predict the classes of new data. In order to work, the variables should be normally distributed and each variable should have the same variance. Therefore scaled boston data is used. LDA model is created below and Crime is the target variable.
lda.fit <- lda(crime~., data = train)
lda.fit
## Call:
## lda(crime ~ ., data = train)
##
## Prior probabilities of groups:
## low med_low med_high high
## 0.2500000 0.2351485 0.2524752 0.2623762
##
## Group means:
## zn indus chas nox rm
## low 0.94532315 -0.9015422 -0.11640431 -0.8757529 0.46805101
## med_low -0.09322187 -0.3194004 -0.06511327 -0.5804788 -0.10289750
## med_high -0.40316737 0.2139297 0.26805724 0.3934257 0.09358976
## high -0.48724019 1.0170298 -0.01233188 1.0627931 -0.43480623
## age dis rad tax ptratio black
## low -0.8679686 0.8810682 -0.7021456 -0.7778615 -0.4610314 0.3806579
## med_low -0.3563818 0.3699037 -0.5406181 -0.4583422 -0.0387791 0.3490964
## med_high 0.4750166 -0.4165883 -0.4076377 -0.2947038 -0.2593211 0.1326062
## high 0.8152280 -0.8518187 1.6390172 1.5146914 0.7818116 -0.7636429
## lstat medv
## low -0.77137128 0.557845161
## med_low -0.17603311 0.006619245
## med_high 0.04192482 0.172959126
## high 0.80486593 -0.616967657
##
## Coefficients of linear discriminants:
## LD1 LD2 LD3
## zn 0.10445586 0.67243379 -1.10279041
## indus -0.01145657 -0.18517832 0.04248002
## chas -0.07532563 -0.09913915 0.02156931
## nox 0.39248208 -0.53968683 -1.24980445
## rm -0.13203513 -0.05777897 -0.17127233
## age 0.29964831 -0.41144686 -0.25135410
## dis -0.06804973 -0.12264372 0.20239735
## rad 3.09043975 1.01846123 -0.36886535
## tax 0.09924878 -0.13885871 1.05892720
## ptratio 0.10976417 0.06459718 -0.29811700
## black -0.16594816 0.01711781 0.16183815
## lstat 0.16883947 -0.18317621 0.34359110
## medv 0.19185891 -0.25093864 -0.18265340
##
## Proportion of trace:
## LD1 LD2 LD3
## 0.9495 0.0373 0.0132
# the function for lda biplot arrows
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "red", tex = 0.75, choices = c(1,2)){
heads <- coef(x)
arrows(x0 = 0, y0 = 0,
x1 = myscale * heads[,choices[1]],
y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
text(myscale * heads[,choices], labels = row.names(heads),
cex = tex, col=color, pos=3)
}
# target classes as numeric
classes <- as.numeric(train$crime)
Prior probabilities tell how training observations fell to crime categories. All probabilities are around 25 %. Group means show the mean value of each group by each variable. Coefficients of linear discriminants provides the linear combinations that are used to form the LDA decision rule. For instance, 0.131033364 * zn + 0.047138924 * indus ….0.237478243 * medv is the rule for LD1. Index of accessibility to radial highways (rad) has the largest coefficient value meaning it contibutes most. Average number of rooms per dwelling (rm) has the smallest coefficient; bigger houses with more rooms tend to locate on areas of low crime rates.Fit between proportion of trace fit between group variants
Proportion of trace is the percentage separation that each of the discriminant achieves. LD1 achieves already 95 %, when LD2 and LD 3 have only 4 % and 1 %. This means that the first linear discrimination is already enough.
There is a LDA biplot below.The biplot visualizes how variable rad contributes a lot in LD1 and it is contributing a lot also in LD2. Variable nox contributes in LD1 positively and in LD2 negatively, which was also seen from coefficients. Zn contributes in LD2, but not much in LD1. Other variables are around zero and do not stand out.
# plot the lda results
plot(lda.fit, dimen = 2, col=classes, pch=classes)
lda.arrows(lda.fit, myscale = 1)
lda.pred <- predict(lda.fit, newdata = test)
Next correct classes are saved and categorical variable is removed: correct_classes <- test$crime test <- dplyr::select(test, -crime)
Crime categories are cross tabulated by correct and predicted values. High values are well predicted. Lowest values were well predicted as well. Low med and high med categories have more incorrect predictions, but also for them most predictions went right.
# cross tabulate the results
table(correct = correct_classes, predicted = lda.pred$class)
## predicted
## correct low med_low med_high high
## low 15 11 0 0
## med_low 6 20 5 0
## med_high 1 6 16 1
## high 0 0 0 21
Boston dataset is reloaded again and the done modifications are not valid any more. Data is standardized by using scale function. Scaling was successfull, means are 0.
library(MASS)
data("Boston")
boston_scaled2 <- scale(Boston)
summary(boston_scaled2)
## crim zn indus
## Min. :-0.419367 Min. :-0.48724 Min. :-1.5563
## 1st Qu.:-0.410563 1st Qu.:-0.48724 1st Qu.:-0.8668
## Median :-0.390280 Median :-0.48724 Median :-0.2109
## Mean : 0.000000 Mean : 0.00000 Mean : 0.0000
## 3rd Qu.: 0.007389 3rd Qu.: 0.04872 3rd Qu.: 1.0150
## Max. : 9.924110 Max. : 3.80047 Max. : 2.4202
## chas nox rm age
## Min. :-0.2723 Min. :-1.4644 Min. :-3.8764 Min. :-2.3331
## 1st Qu.:-0.2723 1st Qu.:-0.9121 1st Qu.:-0.5681 1st Qu.:-0.8366
## Median :-0.2723 Median :-0.1441 Median :-0.1084 Median : 0.3171
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.:-0.2723 3rd Qu.: 0.5981 3rd Qu.: 0.4823 3rd Qu.: 0.9059
## Max. : 3.6648 Max. : 2.7296 Max. : 3.5515 Max. : 1.1164
## dis rad tax ptratio
## Min. :-1.2658 Min. :-0.9819 Min. :-1.3127 Min. :-2.7047
## 1st Qu.:-0.8049 1st Qu.:-0.6373 1st Qu.:-0.7668 1st Qu.:-0.4876
## Median :-0.2790 Median :-0.5225 Median :-0.4642 Median : 0.2746
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.6617 3rd Qu.: 1.6596 3rd Qu.: 1.5294 3rd Qu.: 0.8058
## Max. : 3.9566 Max. : 1.6596 Max. : 1.7964 Max. : 1.6372
## black lstat medv
## Min. :-3.9033 Min. :-1.5296 Min. :-1.9063
## 1st Qu.: 0.2049 1st Qu.:-0.7986 1st Qu.:-0.5989
## Median : 0.3808 Median :-0.1811 Median :-0.1449
## Mean : 0.0000 Mean : 0.0000 Mean : 0.0000
## 3rd Qu.: 0.4332 3rd Qu.: 0.6024 3rd Qu.: 0.2683
## Max. : 0.4406 Max. : 3.5453 Max. : 2.9865
class(boston_scaled2)
## [1] "matrix"
boston_scaled2<-as.data.frame(boston_scaled2)
Distances calculation:
dist_eu<- dist(boston_scaled2)
summary(dist_eu)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 0.1343 3.4625 4.8241 4.9111 6.1863 14.3970
Kmeans clustering and pairs are calculated, but the number of centers here is 4, which is just a guess what could be the optimal number.
km4 <-kmeans(boston_scaled2, centers = 4)
pairs(boston_scaled2, col = km4$cluster)
str(km4)
## List of 9
## $ cluster : Named int [1:506] 4 1 4 4 4 1 1 1 1 1 ...
## ..- attr(*, "names")= chr [1:506] "1" "2" "3" "4" ...
## $ centers : num [1:4, 1:14] -0.379 1.917 0.392 -0.399 -0.355 ...
## ..- attr(*, "dimnames")=List of 2
## .. ..$ : chr [1:4] "1" "2" "3" "4"
## .. ..$ : chr [1:14] "crim" "zn" "indus" "chas" ...
## $ totss : num 7070
## $ withinss : num [1:4] 1076 395 993 1021
## $ tot.withinss: num 3486
## $ betweenss : num 3584
## $ size : int [1:4] 212 42 127 125
## $ iter : int 3
## $ ifault : int 0
## - attr(*, "class")= chr "kmeans"
km4
## K-means clustering with 4 clusters of sizes 212, 42, 127, 125
##
## Cluster means:
## crim zn indus chas nox rm
## 1 -0.379470 -0.3553728 -0.3254942 0.006239345 -0.3875041 -0.2347120
## 2 1.916757 -0.4872402 1.0201311 -0.272329068 1.0484799 -0.4122561
## 3 0.392245 -0.4872402 1.1697122 0.099680403 1.1439383 -0.4650169
## 4 -0.398970 1.2614609 -0.9791535 -0.020354653 -0.8573235 1.0090468
## age dis rad tax ptratio black
## 1 -0.07470041 0.1204023 -0.5836998 -0.6025848 -0.006695716 0.2801081
## 2 0.78947129 -0.8908848 1.6076484 1.4922585 0.745290819 -2.8449572
## 3 0.80978018 -0.8411778 1.0202595 1.1728009 0.554458254 0.1236280
## 4 -0.96130713 0.9497716 -0.5867985 -0.6709807 -0.802391366 0.3552363
## lstat medv
## 1 -0.1150795 -0.0935769
## 2 1.2421501 -1.1216726
## 3 0.7233656 -0.5227308
## 4 -0.9571271 1.0666829
##
## Clustering vector:
## 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
## 4 1 4 4 4 1 1 1 1 1 1 1 1 1 1 1 1 1
## 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
## 1 1 1 4 4 4 1 1 1 1 1 1 1 1 1 1 4 4
## 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
## 4 4 4 4 4 1 1 1 1 4 4 4 4 1 1 1 1 1
## 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
## 1 1 1 1 1 1 1 1 4 1 4 1 1 1 1 1 1 1
## 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
## 1 1 1 1 1 1 1 4 4 4 1 1 1 1 1 1 1 1
## 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
## 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
## 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
## 3 3 3 3 3 3 3 3 3 3 3 3 2 1 1 3 1 4
## 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
## 4 4 1 1 4 1 1 1 1 1 1 1 1 1 1 1 1 4
## 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
## 4 1 1 1 1 1 4 4 4 4 4 4 4 4 4 4 4 4
## 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
## 4 4 4 4 4 4 4 1 1 1 1 1 1 1 1 1 1 1
## 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
## 1 1 1 1 1 1 1 1 4 4 4 1 4 4 1 1 4 4
## 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
## 1 1 1 4 4 4 4 1 4 4 1 1 4 1 4 4 4 4
## 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
## 4 4 4 4 4 4 4 1 4 4 4 4 4 1 1 4 4 1
## 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
## 1 4 1 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4
## 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
## 4 4 4 4 4 1 1 4 1 1 4 4 4 4 4 4 4 4
## 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
## 4 4 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
## 1 1 1 1 1 1 1 1 4 1 1 1 1 1 1 1 1 4
## 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
## 1 4 4 1 1 4 4 4 4 4 4 4 4 4 3 3 3 3
## 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
## 3 3 3 3 3 3 3 2 3 3 3 3 3 3 3 3 3 3
## 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
## 3 3 2 3 3 3 2 3 3 3 3 3 3 3 3 3 3 3
## 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
## 3 3 2 3 3 3 3 3 2 2 3 3 3 2 2 2 2 2
## 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
## 2 2 2 2 2 2 3 3 3 2 2 2 2 2 2 2 2 2
## 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
## 2 2 2 2 2 2 2 3 3 3 3 3 2 2 3 3 3 3
## 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
## 2 3 3 3 2 2 2 2 3 3 3 3 3 3 3 3 2 3
## 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
## 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3
## 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
## 3 3 3 3 3 3 3 1 1 1 1 1 1 1 1 1 1 1
## 505 506
## 1 1
##
## Within cluster sum of squares by cluster:
## [1] 1076.0728 395.1207 993.4513 1021.4228
## (between_SS / total_SS = 50.7 %)
##
## Available components:
##
## [1] "cluster" "centers" "totss" "withinss"
## [5] "tot.withinss" "betweenss" "size" "iter"
## [9] "ifault"
Finding the optimal number of clusters is not irrelevant question and the textbook recommends the method to plot within-group sum of squares associated with the k-means solution for each number of groups. Then the “elbow” in the picture gives indication of the most useful solution. The plot below indicates that the elbow is in 2, after 2 the decrease is slower. However, even with 3 it is still significant but I choose to use 2.
set.seed(123)
# determine the number of clusters
k_max <- 10
# calculate the total within sum of squares
twcss <- sapply(1:k_max, function(k){kmeans(boston_scaled2, k)$tot.withinss})
# visualize the results
qplot(x = 1:k_max, y = twcss, geom = 'line', main="WGSS and groups in K-means solution")
Only 51 % total variance in data set that is explained by the first clustering with 4 clusters, which is not impressive. I checked how many clusters I should have to gain 80 % of total variance and it was 20. It is clear that it is too much, so I still keep 2 clusters, although the biggest decrease of variation ends at 2. In real-life I should check the correct number of clusters also by other methods, e.g. silhouette.
km <-kmeans(boston_scaled2, centers = 2)
pairs(boston_scaled2, col = km$cluster)
Cluster visualization with 2 clusters is clearer than the first guess of 4.
str(km)
## List of 9
## $ cluster : Named int [1:506] 1 1 1 1 1 1 1 1 1 1 ...
## ..- attr(*, "names")= chr [1:506] "1" "2" "3" "4" ...
## $ centers : num [1:2, 1:14] -0.389 0.724 0.262 -0.487 -0.615 ...
## ..- attr(*, "dimnames")=List of 2
## .. ..$ : chr [1:2] "1" "2"
## .. ..$ : chr [1:14] "crim" "zn" "indus" "chas" ...
## $ totss : num 7070
## $ withinss : num [1:2] 2686 1891
## $ tot.withinss: num 4577
## $ betweenss : num 2493
## $ size : int [1:2] 329 177
## $ iter : int 1
## $ ifault : int 0
## - attr(*, "class")= chr "kmeans"
km
## K-means clustering with 2 clusters of sizes 329, 177
##
## Cluster means:
## crim zn indus chas nox rm
## 1 -0.3894158 0.2621323 -0.6146857 0.002908943 -0.5823397 0.2446705
## 2 0.7238295 -0.4872402 1.1425514 -0.005407018 1.0824279 -0.4547830
## age dis rad tax ptratio black
## 1 -0.4331555 0.4540421 -0.5828749 -0.6291043 -0.2943707 0.3282754
## 2 0.8051309 -0.8439539 1.0834228 1.1693521 0.5471636 -0.6101842
## lstat medv
## 1 -0.4530491 0.3532917
## 2 0.8421083 -0.6566834
##
## Clustering vector:
## 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 1 1 1
## 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 1
## 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
## 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
## 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
## 2 2 2 2 2 2 2 2 2 2 2 2 2 1 1 2 1 1
## 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
## 1 1 1 2 1 2 1 1 2 2 1 1 1 1 1 1 1 1
## 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
## 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
## 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2
## 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
## 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
## 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
## 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
## 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
## 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
## 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
## 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
## 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
## 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
## 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
## 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
## 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
## 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
## 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
## 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 1
## 505 506
## 1 1
##
## Within cluster sum of squares by cluster:
## [1] 2686.045 1890.637
## (between_SS / total_SS = 35.3 %)
##
## Available components:
##
## [1] "cluster" "centers" "totss" "withinss"
## [5] "tot.withinss" "betweenss" "size" "iter"
## [9] "ifault"
The plot picture shows the groups are not equal size, one is 177 and other 329. There are some pairs, in which the grouping seems to work nicely; for instance medvd & lstat, lstat & nox,dis & nox and rm & nox. But for some pairs the groups are unclear, for instance rm&ptratio, age & ptratio, ptratio & lstat.
km <-kmeans(boston_scaled2, centers = 2)
str(km)
## List of 9
## $ cluster : Named int [1:506] 2 2 2 2 2 2 2 2 2 2 ...
## ..- attr(*, "names")= chr [1:506] "1" "2" "3" "4" ...
## $ centers : num [1:2, 1:14] 0.724 -0.389 -0.487 0.262 1.143 ...
## ..- attr(*, "dimnames")=List of 2
## .. ..$ : chr [1:2] "1" "2"
## .. ..$ : chr [1:14] "crim" "zn" "indus" "chas" ...
## $ totss : num 7070
## $ withinss : num [1:2] 1891 2686
## $ tot.withinss: num 4577
## $ betweenss : num 2493
## $ size : int [1:2] 177 329
## $ iter : int 1
## $ ifault : int 0
## - attr(*, "class")= chr "kmeans"
Start again with data reloading and scaling
library(MASS)
library(ggplot2)
library(tidyr)
library(cluster)
data("Boston")
boston_scaled3 <- scale(Boston)
boston_scaled3<-as.data.frame(boston_scaled3)
Number of clusters is selected to be 5 and clusters are target classess.
km_4 <-kmeans(boston_scaled3, centers = 5)
lda.fit2 <- lda(km_4$cluster ~., data = boston_scaled3)
lda.fit2
## Call:
## lda(km_4$cluster ~ ., data = boston_scaled3)
##
## Prior probabilities of groups:
## 1 2 3 4 5
## 0.25296443 0.21146245 0.31027668 0.09881423 0.12648221
##
## Group means:
## crim zn indus chas nox rm
## 1 1.0878724 -0.4872402 1.0149946 -0.1492947 1.0187219 -0.4210063
## 2 -0.3243708 -0.4822312 0.6185681 0.1324196 0.4947716 -0.5346882
## 3 -0.3981592 -0.1664810 -0.6090235 -0.2221749 -0.6655615 -0.1199301
## 4 -0.3103881 -0.1159242 -0.4991257 1.0662850 -0.0692028 1.6606848
## 5 -0.4142124 2.2796750 -1.1802049 -0.2108119 -1.1778698 0.7327381
## age dis rad tax ptratio black
## 1 0.7521154 -0.8135370 1.6596029 1.5294129 0.8057784 -0.7784115
## 2 0.7503783 -0.5640394 -0.5954711 -0.1985406 0.1042866 0.0419631
## 3 -0.6336330 0.5362710 -0.5817365 -0.7039306 -0.0756665 0.3655348
## 4 0.2630692 -0.4217934 -0.3042757 -0.5487050 -0.9864145 0.3028535
## 5 -1.4099114 1.5840638 -0.6588648 -0.5713854 -0.8296553 0.3533591
## lstat medv
## 1 0.8914421 -0.75669132
## 2 0.5669361 -0.49061591
## 3 -0.4149421 0.05516096
## 4 -0.9553010 1.76459824
## 5 -0.9664968 0.81972201
##
## Coefficients of linear discriminants:
## LD1 LD2 LD3 LD4
## crim -0.053751141 0.179074873 0.13780108 -0.07519738
## zn 0.062843967 1.465907935 -0.50908589 1.32076958
## indus -0.179836757 -0.391770295 -0.40486479 0.39138090
## chas 0.230845551 -0.111364285 0.41752818 0.17516588
## nox 0.076978215 -0.081264681 -0.04255968 0.44218751
## rm -0.111320904 0.164332062 0.59726088 0.22808090
## age -0.048463133 -0.522072143 0.34421689 0.63414099
## dis 0.291886353 0.306401440 -0.21018069 -0.27013447
## rad -4.160201638 1.135383393 0.44562029 -1.62967439
## tax 0.204066630 0.381083248 -0.11925476 1.00108406
## ptratio 0.009872979 -0.170859777 -0.22250511 0.33481849
## black 0.025657288 0.005723222 -0.01480980 -0.08944504
## lstat -0.105055816 -0.045731798 0.14150418 0.39609928
## medv 0.351343258 0.268482029 0.88984740 0.30142226
##
## Proportion of trace:
## LD1 LD2 LD3 LD4
## 0.7423 0.1680 0.0517 0.0381
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "red", tex = 0.75, choices = c(1,2)){
heads <- coef(x)
arrows(x0 = 0, y0 = 0,
x1 = myscale * heads[,choices[1]],
y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
text(myscale * heads[,choices], labels = row.names(heads),
cex = tex, col=color, pos=3)
}
Biplot drawing next:
plot(lda.fit2, dimen = 2, col=classes, pch=classes)
lda.arrows(lda.fit2, myscale = 1)
Everytime the model is run again, the results change. But rad and zn are standing out, also chas every so often. Arrows for each variable point in the direction of increasing values of that variable.Rad increases meaning higher the value, the more meaningful it is in clustering where it is pointin. Otherwise all variables are around zero meaning they are not influencial
I copied the lines from the instructions and did the package installation
model_predictors <- dplyr::select(train, -crime)
# check the dimensions
dim(model_predictors)
## [1] 404 13
dim(lda.fit$scaling)
## [1] 13 3
# matrix multiplication
matrix_product <- as.matrix(model_predictors) %*% lda.fit$scaling
matrix_product <- as.data.frame(matrix_product)
Then I tried plotting as instucted
library(plotly)
##
## Attaching package: 'plotly'
## The following object is masked from 'package:MASS':
##
## select
## The following object is masked from 'package:ggplot2':
##
## last_plot
## The following object is masked from 'package:stats':
##
## filter
## The following object is masked from 'package:graphics':
##
## layout
plot_ly(x = matrix_product$LD1, y = matrix_product$LD2, z = matrix_product$LD3, type= 'scatter3d', mode='markers')
However, at this point I run into trouble with WebGL. In the help page the cube is rolling but I just did not succeed in R Studio.
hd <- read.csv("http://s3.amazonaws.com/assets.datacamp.com/production/course_2218/datasets/human_development.csv", stringsAsFactors = F)
gii <- read.csv("http://s3.amazonaws.com/assets.datacamp.com/production/course_2218/datasets/gender_inequality.csv", stringsAsFactors = F, na.strings = "..")
#checking the dimension
dim(hd)
## [1] 195 8
dim(gii)
## [1] 195 10
#checking the structure
str(hd)
## 'data.frame': 195 obs. of 8 variables:
## $ HDI.Rank : int 1 2 3 4 5 6 6 8 9 9 ...
## $ Country : chr "Norway" "Australia" "Switzerland" "Denmark" ...
## $ Human.Development.Index..HDI. : num 0.944 0.935 0.93 0.923 0.922 0.916 0.916 0.915 0.913 0.913 ...
## $ Life.Expectancy.at.Birth : num 81.6 82.4 83 80.2 81.6 80.9 80.9 79.1 82 81.8 ...
## $ Expected.Years.of.Education : num 17.5 20.2 15.8 18.7 17.9 16.5 18.6 16.5 15.9 19.2 ...
## $ Mean.Years.of.Education : num 12.6 13 12.8 12.7 11.9 13.1 12.2 12.9 13 12.5 ...
## $ Gross.National.Income..GNI..per.Capita: chr "64,992" "42,261" "56,431" "44,025" ...
## $ GNI.per.Capita.Rank.Minus.HDI.Rank : int 5 17 6 11 9 11 16 3 11 23 ...
str(gii)
## 'data.frame': 195 obs. of 10 variables:
## $ GII.Rank : int 1 2 3 4 5 6 6 8 9 9 ...
## $ Country : chr "Norway" "Australia" "Switzerland" "Denmark" ...
## $ Gender.Inequality.Index..GII. : num 0.067 0.11 0.028 0.048 0.062 0.041 0.113 0.28 0.129 0.157 ...
## $ Maternal.Mortality.Ratio : int 4 6 6 5 6 7 9 28 11 8 ...
## $ Adolescent.Birth.Rate : num 7.8 12.1 1.9 5.1 6.2 3.8 8.2 31 14.5 25.3 ...
## $ Percent.Representation.in.Parliament : num 39.6 30.5 28.5 38 36.9 36.9 19.9 19.4 28.2 31.4 ...
## $ Population.with.Secondary.Education..Female.: num 97.4 94.3 95 95.5 87.7 96.3 80.5 95.1 100 95 ...
## $ Population.with.Secondary.Education..Male. : num 96.7 94.6 96.6 96.6 90.5 97 78.6 94.8 100 95.3 ...
## $ Labour.Force.Participation.Rate..Female. : num 61.2 58.8 61.8 58.7 58.5 53.6 53.1 56.3 61.6 62 ...
## $ Labour.Force.Participation.Rate..Male. : num 68.7 71.8 74.9 66.4 70.6 66.4 68.1 68.9 71 73.8 ...
summary(hd)
## HDI.Rank Country Human.Development.Index..HDI.
## Min. : 1.00 Length:195 Min. :0.3480
## 1st Qu.: 47.75 Class :character 1st Qu.:0.5770
## Median : 94.00 Mode :character Median :0.7210
## Mean : 94.31 Mean :0.6918
## 3rd Qu.:141.25 3rd Qu.:0.8000
## Max. :188.00 Max. :0.9440
## NA's :7
## Life.Expectancy.at.Birth Expected.Years.of.Education
## Min. :49.00 Min. : 4.10
## 1st Qu.:65.75 1st Qu.:11.10
## Median :73.10 Median :13.10
## Mean :71.07 Mean :12.86
## 3rd Qu.:76.80 3rd Qu.:14.90
## Max. :84.00 Max. :20.20
##
## Mean.Years.of.Education Gross.National.Income..GNI..per.Capita
## Min. : 1.400 Length:195
## 1st Qu.: 5.550 Class :character
## Median : 8.400 Mode :character
## Mean : 8.079
## 3rd Qu.:10.600
## Max. :13.100
##
## GNI.per.Capita.Rank.Minus.HDI.Rank
## Min. :-84.0000
## 1st Qu.: -9.0000
## Median : 1.5000
## Mean : 0.1862
## 3rd Qu.: 11.0000
## Max. : 47.0000
## NA's :7
summary(gii)
## GII.Rank Country Gender.Inequality.Index..GII.
## Min. : 1.00 Length:195 Min. :0.0160
## 1st Qu.: 47.75 Class :character 1st Qu.:0.2030
## Median : 94.00 Mode :character Median :0.3935
## Mean : 94.31 Mean :0.3695
## 3rd Qu.:141.25 3rd Qu.:0.5272
## Max. :188.00 Max. :0.7440
## NA's :7 NA's :33
## Maternal.Mortality.Ratio Adolescent.Birth.Rate
## Min. : 1.0 Min. : 0.60
## 1st Qu.: 16.0 1st Qu.: 15.45
## Median : 69.0 Median : 40.95
## Mean : 163.2 Mean : 49.55
## 3rd Qu.: 230.0 3rd Qu.: 71.78
## Max. :1100.0 Max. :204.80
## NA's :10 NA's :5
## Percent.Representation.in.Parliament
## Min. : 0.00
## 1st Qu.:12.47
## Median :19.50
## Mean :20.60
## 3rd Qu.:27.02
## Max. :57.50
## NA's :3
## Population.with.Secondary.Education..Female.
## Min. : 0.9
## 1st Qu.: 27.8
## Median : 55.7
## Mean : 54.8
## 3rd Qu.: 81.8
## Max. :100.0
## NA's :26
## Population.with.Secondary.Education..Male.
## Min. : 3.20
## 1st Qu.: 38.30
## Median : 60.00
## Mean : 60.29
## 3rd Qu.: 85.80
## Max. :100.00
## NA's :26
## Labour.Force.Participation.Rate..Female.
## Min. :13.50
## 1st Qu.:44.50
## Median :53.30
## Mean :52.61
## 3rd Qu.:62.62
## Max. :88.10
## NA's :11
## Labour.Force.Participation.Rate..Male.
## Min. :44.20
## 1st Qu.:68.88
## Median :75.55
## Mean :74.74
## 3rd Qu.:80.15
## Max. :95.50
## NA's :11
Renaming the columns:
names(hd)[names(hd) == "Human.Development.Index..HDI."] <- "HDI"
names(hd)[names(hd) == "Expected.Years.of.Education"] <- "EYE"
names(hd)[names(hd) == "Life.Expectancy.at.Birth"] <- "LEB"
names(hd)[names(hd) == "Mean.Years.of.Education"] <- "MYE"
names(hd)[names(hd) == "Gender.Inequality.Index..GII."] <- "GII"
names(hd)[names(hd) == "Maternal.Mortality.Ratio"] <- "MMR"
names(hd)[names(hd) == "Percent.Representation.in.Parliament"] <- "PerParliament"
names(hd)[names(hd) == "Population.with.Secondary.Education..Female."] <- "SecEducFemal"
names(hd)[names(hd) == "Gross.National.Income..GNI..per.Capita"] <- "GNIncPerCap"
names(hd)[names(hd) == "GNI.per.Capita.Rank.Minus.HDI.Rank"] <- "GNIMinusHDIRank"
names(gii)[names(gii) == "Adolescent.Birth.Rate"] <- "ADBR"
names(gii)[names(gii) == "Expected.Years.of.Education"] <- "EYE"
names(gii)[names(gii) == "Life.Expectancy.at.Birth"] <- "LEB"
names(gii)[names(gii) == "Mean.Years.of.Education"] <- "MYE"
names(gii)[names(gii) == "Gender.Inequality.Index..GII."] <- "GII"
names(gii)[names(gii) == "Maternal.Mortality.Ratio"] <- "MMR"
names(gii)[names(gii) == "Percent.Representation.in.Parliament"] <- "PerParliament"
names(gii)[names(gii) == "Population.with.Secondary.Education..Male."] <- "SecEducMale"
names(gii)[names(gii) == "Population.with.Secondary.Education..Female."] <- "SecEducFemal"
names(gii)[names(gii) == "Gross.National.Income..GNI..per.Capita"] <- "GNIncPerCap"
names(gii)[names(gii) == "Labour.Force.Participation.Rate..Female."] <- "LabForParFem"
names(gii)[names(gii) == "Labour.Force.Participation.Rate..Male."] <- "LabForParMale"
head(hd)
## HDI.Rank Country HDI LEB EYE MYE GNIncPerCap GNIMinusHDIRank
## 1 1 Norway 0.944 81.6 17.5 12.6 64,992 5
## 2 2 Australia 0.935 82.4 20.2 13.0 42,261 17
## 3 3 Switzerland 0.930 83.0 15.8 12.8 56,431 6
## 4 4 Denmark 0.923 80.2 18.7 12.7 44,025 11
## 5 5 Netherlands 0.922 81.6 17.9 11.9 45,435 9
## 6 6 Germany 0.916 80.9 16.5 13.1 43,919 11
head(gii)
## GII.Rank Country GII MMR ADBR PerParliament SecEducFemal
## 1 1 Norway 0.067 4 7.8 39.6 97.4
## 2 2 Australia 0.110 6 12.1 30.5 94.3
## 3 3 Switzerland 0.028 6 1.9 28.5 95.0
## 4 4 Denmark 0.048 5 5.1 38.0 95.5
## 5 5 Netherlands 0.062 6 6.2 36.9 87.7
## 6 6 Germany 0.041 7 3.8 36.9 96.3
## SecEducMale LabForParFem LabForParMale
## 1 96.7 61.2 68.7
## 2 94.6 58.8 71.8
## 3 96.6 61.8 74.9
## 4 96.6 58.7 66.4
## 5 90.5 58.5 70.6
## 6 97.0 53.6 66.4